package com.jinhongone.pattern.creater.singleton.demo7;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;

/*
 * 上述单例方式，除枚举方式外存在序列化安全问题
 * */
public class Test {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        Singleton instance = Singleton.getInstance();
        seri(instance);
        Singleton i1 = unseri();
        Singleton i2 = unseri();
//      Singletonm没有readResolve()方法时结果为false，每次从新new对象，有了该方法反序列化返回该方法返回值
        System.out.println(Objects.equals(i1, i2));

    }

    public static void seri(Singleton singleton) throws IOException {
        ObjectOutputStream output = new ObjectOutputStream(Files.newOutputStream(Paths.get("D:\\javaCode\\workspace\\design-pattern\\src\\main\\java\\com\\jinhongone\\pattern\\creater\\singleton\\demo7\\a.txt")));
        output.writeObject(singleton);
        output.close();
    }

    public static Singleton unseri() throws IOException, ClassNotFoundException {
        ObjectInputStream inputStream = new ObjectInputStream(Files.newInputStream(Paths.get("D:\\javaCode\\workspace\\design-pattern\\src\\main\\java\\com\\jinhongone\\pattern\\creater\\singleton\\demo7\\a.txt")));
        Singleton o = (Singleton) inputStream.readObject();
        System.out.println("反序列化对象：" + o);
        inputStream.close();
        return o;
    }
}
